package com.wy.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description IPGlobalFilter
 * author wy
 * date 2021-09-05 22:44
 **/
@Component
public class IPGlobalFilter implements GlobalFilter, Ordered
{
    private int maxTimes = 5;
    private int limitMinutes = 1;

    private static Map<String, List<Long>> ipCache = new HashMap<>();

    public IPGlobalFilter() {
        System.out.println("IPGlobalFilter init");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println(maxTimes);
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 客户端IP
        String ip = request.getRemoteAddress().getHostString();

        // 设限服务把本次请求加入缓存
        List<Long> currentIpCache = ipCache.get(ip);
        // 初始化当前ip请求记录
        if (currentIpCache == null) {
            currentIpCache = new ArrayList<>();
            ipCache.put(ip, currentIpCache);
        }
        currentIpCache.add(System.currentTimeMillis());
        // 计算limitMinutes内访问次数是否超过maxTimes
        int count = 0;
        long startTime = System.currentTimeMillis() - (limitMinutes * 60 * 1000);
        for (Long reqTime : currentIpCache) {
            if (reqTime > startTime) {
                count++;
            }
        }
        if (count > maxTimes) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            String data = "you request too quick！";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
